package org.mtmi.ui.scenes.actions;

import java.io.File;

import org.mtmi.ui.IMG;
import org.mtmi.ui.M;
import org.mtmi.ui.actions.Action;
import org.mtmi.ui.controls.listeners.PopupListener;
import org.mtmi.ui.controls.popups.AbstractButtonPopup;
import org.mtmi.ui.controls.popups.TwoButtonsPopup;
import org.mtmi.ui.drawables.IDrawable;
import org.mtmi.ui.scenes.ISceneManagerListener;
import org.mtmi.ui.scenes.Scene;
import org.mtmi.ui.scenes.SceneManager;

/**
 * Add control to current scene.
 */
public class RemoveSceneAction extends Action
  implements ISceneManagerListener
{
	private IDrawable image;
	
	public RemoveSceneAction() {
		super( PUSH );
		SceneManager.getDefault().addSceneManagerListener( this );
	}
	
	@Override
	public String getText() {
		return "Remove Scene";
	}
	
	@Override
	public IDrawable getImage() {
		if( image==null ) {
			image = IMG.GetD( IMG.I_SCENE_DEL );
		}
		return image;
	}
	
	@Override
	public boolean isEnabled() {
		//cannot remove the last scene
		return SceneManager.getDefault().hasPrevious() || SceneManager.getDefault().hasNext();
	}
	
	@Override
	public void run() {
		final Scene scene = SceneManager.getDefault().getScene();
		final TwoButtonsPopup p = new TwoButtonsPopup( scene,
				"Remove Current Scene ?", new String[] { "Yes", "No" },
				M.SCENE_EDITOR_CONTROL );
		p.addResponseListener( new PopupListener() {
			@Override
			public void popupButtonSelected(int id) {
				if( id == AbstractButtonPopup.OK ) {
					doRemoveScene( scene );
				}
			}
		});
	}
	
	private void doRemoveScene( Scene scene ) {
		SceneManager.getDefault().removeScene( scene );
		
		//file file is also renamed .. if exists
		String dir = SceneManager.getDefault().getSceneDirectory();
		if( scene.getFileName()!=null && dir!=null ) {
			String fullname = dir+File.separator+scene.getFileName();
			File f = new File( fullname );
			if( f.exists() ) {
				File ren = new File( fullname+".removed" );
				if( ! f.renameTo( ren ) ) {
					System.err.println(">> CANNOT RENAME FILE "+scene.getFileName());
				}
			}
		}
	}

	@Override
	public void sceneManagerModeChanged(boolean edit) {}

	@Override
	public void sceneManagerSceneChanged(Scene newScene, Scene oldScene) {}

	@Override
	public void sceneManagerSceneAdded(Scene sceneAdded) {
		if( SceneManager.getDefault().getSceneCount()>1 ) update();
	}

	@Override
	public void sceneManagerSceneRemoved(Scene sceneRemoved) {
		if( SceneManager.getDefault().getSceneCount()==1 ) update();
	}

}
